'''
华夏常青藤老年防癌保障计划
'''
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from decimal import Decimal

class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "华夏常青藤防癌医疗保险"


    # 生成产品数据
    def genProductInfo(self):

        #年龄段
        years = [ str(i) for i in range(45,71)]

        #性别0 男 1 女
        gender = ["0","1"]

        #保障金额
        feedback = ["10","20"]

        #保险期间
        interval = ["10","20"]

        #缴费期间
        paytimes = ["10","20"]

        #搭配险种
        # 常青藤防癌医疗保险
        ext_cancer = [0,1]
        # 附加险
        ext_some = [1,0]

        for v in product(

            years,gender,feedback,interval,paytimes,ext_cancer,ext_some
        # 只有防癌保险为1 才有附加险
        ):

            # 写入数据库
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3],v[4],v[5],v[6]))
            self.mysql._conn.commit()


    #爬虫
    def requestJson(self,dt=None):

        # 随机领取一条任务


        data = {

            "age": dt["year"],
            "sex": dt["gender"],
            "bt":  dt["interval"],
            "pt":  dt["paytime"]

        }


        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=data)

        if r.status_code == 200 and r.json()["success"] == "true":

            back_price = r.json()["value"]

            print( "官方返回价格：",back_price )
            #第一种情况 保障金额为20w 没有附加险
            if dt["feedback"] == "20" and  dt["pre_cancer"] == 0:

                totalPrice = str(float(r.json()["value"]) * 100 * 2 )

                print( totalPrice )

                data = {

                    "name":self.name,
                    "id":dt["id"],
                    "price":Decimal( totalPrice ).quantize(Decimal('0.00'))

                }

                self.mysql.updatePrice( data )

                print("无任何附加保险,保障金额为20w保险产品价格更新成功:",dt["id"])

                return None

            #第二种情况 保证金为10w 没有附加险
            elif dt["feedback"] == "10" and  dt["pre_cancer"] == 0:

                print("保障金10w 没有附加保险：",dt["id"])

                totalPrice = str(float(r.json()["value"])*100)

                data = {

                    "name": self.name,
                    "id": dt["id"],
                    "price": Decimal( totalPrice ).quantize(Decimal('0.00'))
                }

                self.mysql.updatePrice(data)

                print("无任何附加保险,保障金额为10w保险产品价格更新成功:", dt["id"])

                return None


            # 带有附加险情况 存在附加险
            elif dt["feedback"] == "10" and  dt["pre_cancer"] == 1:

                price = float(r.json()["value"])*100

                #索引出附加保险
                data = {

                    "age":dt["year"],
                    "sex":dt["gender"]
                }

                r = requests.post( url = domain[self.name]["pre_url"] ,headers=domain[self.name]["header"],data=(data) )

                if r.status_code == 200:

                    ext_price = r.json()["value"]["tb"]

                    # 不带有离子险
                    if dt["ext_some"] == 0:

                        totalPrice = price  + float(ext_price)

                        data = {

                            "name": self.name,
                            "id": dt["id"],
                            "price": Decimal( totalPrice ).quantize(Decimal('0.00'))
                        }

                        self.mysql.updatePrice(data)

                        print("保障金额为10w,附带抗癌保险 产品价格更新成功:", dt["id"])

                        return None

                    # 存在离子险 但年龄不能超过55周岁
                    elif dt["ext_some"] == 1:

                        if int( dt["year"] )>55:

                            # 年限超过55岁 数据无效

                            # 无效数据
                            data = {

                                "name": self.name,
                                "id": dt["id"],
                                "state": 3
                            }

                            self.mysql.updateTask(data)

                            print("保障金额10w 年龄超过55岁不具备购买离子保险条件:",dt["id"])

                            return None


                        else:
                            # 获取离子附加险数据
                            data = {
                                "age": dt["year"],
                                "isSocialSecurity": "N",
                                "isContinueInsure": "N",
                                "isAdd":"Y"
                            }

                            r = requests.post( url = domain[self.name]["ext_url"],headers=domain[self.name]["header"],data=data )

                            if r.status_code == 200:

                                ext_some_price = float(r.json()["zz__premium"])

                                totalPrice = price + float( ext_price ) + float( ext_some_price )

                                data = {

                                    "name": self.name,
                                    "id": dt["id"],
                                    "price": Decimal( str(totalPrice) ).quantize(Decimal('0.00'))
                                }

                                print("保障金额为10w,附带抗癌保险和离子险 产品价格更新成功:", dt["id"])

                                self.mysql.updatePrice(data)

                                return None

            # 带有附加险情况 存在附加险
            elif dt["feedback"] == "20" and dt["pre_cancer"] == 1:

                price = float(r.json()["value"]) * 100 *2

                # 索引出附加保险
                data = {

                    "age": dt["year"],
                    "sex": dt["gender"]
                }

                r = requests.post(url=domain[self.name]["pre_url"], headers=domain[self.name]["header"],data=(data))

                if r.status_code == 200:

                    ext_price = r.json()["value"]["tb"]

                    # 不带有离子险
                    if dt["ext_some"] == 0:


                        totalPrice = price + float(ext_price)

                        data = {

                            "name": self.name,
                            "id": dt["id"],
                            "price": Decimal( str(totalPrice) ).quantize(Decimal('0.00'))
                        }

                        self.mysql.updatePrice(data)

                        print("保障金额为20w,附带抗癌保险产品价格更新成功:", dt["id"])

                        return None

                    # 存在离子险 但年龄不能超过55周岁
                    elif dt["ext_some"] == 1:

                        if int(dt["year"]) > 55:

                            # 年限超过55岁 数据无效
                            # 无效数据
                            data = {

                                "name": self.name,
                                "id": dt["id"],
                                "state": 3
                            }

                            self.mysql.updateTask(data)

                            print("保障金额20w 年龄超过55岁不具备购买离子保险条件:", dt["id"])

                            return None


                        else:
                            # 获取离子附加险数据
                            data = {
                                "age": dt["year"],
                                "isSocialSecurity": "N",
                                "isContinueInsure": "N",
                                "isAdd": "Y"
                            }

                            r = requests.post(url=domain[self.name]["ext_url"],headers=domain[self.name]["header"], data=data)


                            if r.status_code == 200:

                                ext_some_price = float(r.json()["zz__premium"])

                                totalPrice = price + float(ext_price) + float(ext_some_price)

                                data = {

                                    "name": self.name,
                                    "id": dt["id"],
                                    "price": Decimal( str(totalPrice) ).quantize(Decimal('0.00'))
                                }

                                self.mysql.updatePrice(data)

                                print("保障金额为20w,附带抗癌保险和离子保险 产品价格更新成功:", dt["id"])

                                return None

        else:

            #无效数据
            data = {

                "name":self.name,
                "id":dt["id"],
                "state":3
            }

            self.mysql.updateTask( data )

            print("不满足当前保险条件:",dt["id"])

            return None


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )


if __name__ == '__main__':

    s = Spider()

    s.main()